//
//  MyCollectionViewController.m
//  PeopleStreet
//
//  Created by 辰领科技 on 16/2/1.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "MyCollectionViewController.h"
#import "SearchStoreTableViewCell.h"
#import "ShoppingProductListCell.h"
#import "ShoppingProductDetailViewController.h"
#import "ShopViewController.h"
#import "FoodsStoreViewController.h"
static NSString *cellIdentify = @"SearchStoreTableViewCell";

static NSString *CellWithIdentifier = @"ShoppingProductListCell";

@interface MyCollectionViewController ()<UITableViewDataSource,UITableViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>{
    NSInteger _totle;
    NSInteger _storeTotle;
}
@property (nonatomic,assign)   NSInteger    pageNO;
@property (nonatomic,assign)   NSInteger    storePageNO;
@property (strong, nonatomic) IBOutlet UIView *navView;
@property (strong, nonatomic) IBOutlet UICollectionView *collectIonView;
@property (strong, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) IBOutlet UIView *changView;
@property (strong, nonatomic) IBOutlet UIButton *goodsCLabel;
@property (strong, nonatomic) IBOutlet UIButton *goodsCButton;
@property (strong, nonatomic) IBOutlet UIButton *shopCLabel;
@property (strong, nonatomic) IBOutlet UIButton *shopCButton;

@property(nonatomic,strong)NSMutableArray * goodsArray;
@property(nonatomic,assign)NSInteger slectedIndex;

@end

@implementation MyCollectionViewController
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (_slectedIndex == 1) {
        // 马上进入刷新状态
        [self.tableView.header beginRefreshing];
    }else{
        // 马上进入刷新状态
        [self.collectIonView.header beginRefreshing];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _slectedIndex = 0;
    _pageNO =1;
    _storePageNO = 1;
    self.goodsArray = [NSMutableArray array];
    [self initViewLayOut];
    [self addRefreshing];
    
    // Do any additional setup after loading the view.
}
- (void)initViewLayOut{
    
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    [self adaptiveViewLayout:self.changView];
    _goodsCButton.selected = YES;
    _goodsCLabel.selected = YES;
    _shopCButton.selected = NO;
    _shopCLabel.selected = NO;
    
    //注册
    
    [self.tableView registerNib:[UINib nibWithNibName:cellIdentify bundle:nil] forCellReuseIdentifier:cellIdentify];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    self.tableView.separatorStyle = NO;
    
    UICollectionViewFlowLayout *flowLayout =[[UICollectionViewFlowLayout alloc]init];
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    flowLayout.minimumInteritemSpacing = 3*VerticalRatio();
    flowLayout.minimumLineSpacing = 3*VerticalRatio();
    self.collectIonView.collectionViewLayout = flowLayout;
    self.collectIonView.userInteractionEnabled=YES;
    self.collectIonView.backgroundColor = [UIColor colorWithWhite:0.953 alpha:1.000];
    [self.collectIonView registerNib:[UINib nibWithNibName:CellWithIdentifier bundle:nil] forCellWithReuseIdentifier:CellWithIdentifier];
}

- (IBAction)back:(id)sender {
    [self.navigationController  popViewControllerAnimated:YES];
}
- (IBAction)goHome:(id)sender {
    [[NSUserDefaults standardUserDefaults]setObject:@"1" forKey:@"ifLogin"];
    [self.navigationController  popViewControllerAnimated:YES];
}



#pragma mark -- 添加刷新数据
- (void)addRefreshing{
    if (_slectedIndex == 1) {
        self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            int64_t delayInSeconds = 8.0;
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                [self.tableView.header endRefreshing];
            });
            self.storePageNO = 1;
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                //请求订单数据
                [self getStoresList];
            });
        }];
        // 马上进入刷新状态
        [self.tableView.header beginRefreshing];
    }else{
    self.collectIonView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        int64_t delayInSeconds = 8.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.collectIonView.header endRefreshing];
        });
        self.pageNO = 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self getGoodsList];
        });
    }];
    // 马上进入刷新状态
    [self.collectIonView.header beginRefreshing];
    }
}
//加载更多数据
- (void)loadMoreData{
    
    if (_slectedIndex==1) {
        if (self.goodsArray.count == _storeTotle) {
            [self.collectIonView.footer endRefreshing];
        }else{
            self.storePageNO = self.storePageNO + 1;
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                //请求订单数据
                [self getStoresList];
            });
        }
    }else{
    if (self.goodsArray.count == _totle) {
        [self.collectIonView.footer endRefreshing];
    }else{
        self.pageNO = self.pageNO + 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self getGoodsList];
        });
    }
    }
}


- (IBAction)changType:(UIButton *)sender {
     _slectedIndex = sender.tag-100;
    if (sender.tag == 100) {
        sender.selected = YES;
        _goodsCLabel.selected = YES;
        _shopCButton.selected = NO;
        _shopCLabel.selected = NO;
        _collectIonView.hidden = NO;
       
        [UIView animateWithDuration:0.5 animations:^{
            _collectIonView.frame = flexibleFrame(CGRectMake(0, 64, 320, 454), NO);
            _tableView.frame = flexibleFrame(CGRectMake(320, 64, 320, 454), NO);
        } completion:^(BOOL finished) {
            _tableView.hidden = YES;
        }];
        
    }else{
        sender.selected = YES;
        _shopCLabel.selected = YES;
        _goodsCLabel.selected = NO;
        _goodsCButton.selected = NO;
        _tableView.hidden = NO;
        [UIView animateWithDuration:0.5 animations:^{
            _collectIonView.frame = flexibleFrame(CGRectMake(-320, 64, 320, 454), NO);
            _tableView.frame = flexibleFrame(CGRectMake(0, 64, 320, 454), NO);
        } completion:^(BOOL finished) {
            _collectIonView.hidden = YES;
        }];
    }
    [self addRefreshing];
}

//收藏商品
- (void)getGoodsList{
    
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic  setObject:[NSNumber numberWithInteger:self.pageNO]     forKey:@"currentPage"];
    [dic  setObject:[NSNumber numberWithInteger:PageSize]       forKey:@"pageSize"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_queryGoodsCollectInfo withHttpType:@"POST" withTag:SX_SX_queryGoodsCollectInfo];
    
}

//收藏店铺
- (void)getStoresList{
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic  setObject:[NSNumber numberWithInteger:self.storePageNO]     forKey:@"currentPage"];
    [dic  setObject:[NSNumber numberWithInteger:PageSize]       forKey:@"pageSize"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_queryStoreCollectInfo withHttpType:@"POST" withTag:SX_SX_queryStoreCollectInfo];
    
}


#pragma mark -- UICollectionViewDataSource
//定义展示的UICollectionViewCell的个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.goodsArray.count;
    
}
//定义展示的Section的个数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(154*VerticalRatio(), 201*VerticalRatio());
}
//定义每个UICollectionView 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 3*VerticalRatio(), 3*VerticalRatio(), 3*VerticalRatio());
    
}
//每个UICollectionView展示的内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ShoppingProductListCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellWithIdentifier forIndexPath:indexPath];
    NSString * image = _goodsArray[indexPath.row][@"appAdertImagUri"];
    if (image.length>0) {
        [cell.imageView sd_setImageWithURL:[NSURL URLWithString: image]];
    }
    
    cell.priceLabel.text = [NSString stringWithFormat:@"￥%@",_goodsArray[indexPath.row][@"mgooPublishPrice"]];
    cell.nameLabel.text = _goodsArray[indexPath.row][@"mgooName"];;
    
    
    return cell;
    
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
    ShoppingProductDetailViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"ShoppingProductDetail"];
    page.goodsId = _goodsArray[indexPath.row][@"mgooId"];
    [self.navigationController   pushViewController:page animated:YES];
    
}



#pragma mark -- UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 95*VerticalRatio();
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return _goodsArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    SearchStoreTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentify];
    if (cell == nil) {
        cell= [[SearchStoreTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentify];
        
    }
    
    for (UIView *view in cell.subviews) {
        if ([view isKindOfClass:[UILabel class]] ||[view isKindOfClass:[UIImageView class]]||[view isKindOfClass:[UIScrollView class]]||[view isKindOfClass:[UIButton class]]) {
            [view removeFromSuperview];
        }
    }
    
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    NSString * image = _goodsArray[indexPath.row][@"mstoImag"];
    if (image.length>0) {
        [cell.storeImage sd_setImageWithURL:[NSURL URLWithString:image]];
    }else{
        cell.storeImage.image = [UIImage imageNamed:@"collection5"];
    }
    cell.storeName.text = _goodsArray[indexPath.row][@"mstoName"];
    cell.storeAddress.text = _goodsArray[indexPath.row][@"mstoAddress"];
    cell.storeTypeLabel.text = [Common stringFromData:_goodsArray[indexPath.row][@"mstoName"]];
    double score;
    if([_goodsArray[indexPath.row][@"storeScore"] isEqual:[NSNull null]]){
        score = 5;
    }else{
        score = [[NSString stringWithFormat:@"%.1f",[_goodsArray[indexPath.row][@"storeScore"]floatValue]/2] doubleValue];
    }
    CommitStarsView * starts = [[CommitStarsView alloc]initWithFrame:flexibleFrame(CGRectMake(118, 37, 75, 15), YES) Stars:score];
    [cell addSubview:starts];
    
    cell.scoreLabel.text = [NSString stringWithFormat:@"%.1f分",score];
    
    
    return cell;
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger storeType = [[Common stringFromData:_goodsArray[indexPath.row][@"mstoStoreType"]] integerValue];
    if (storeType==1) {
        UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
        ShopViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"Shop"];
        page.storeId = _goodsArray[indexPath.row][@"mstoId"];
        [self.navigationController   pushViewController:page animated:YES];
    }else{
        UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
        FoodsStoreViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"FoodsStore"];
        page.foodId = [Common stringFromData:_goodsArray[indexPath.row][@"mstoId"]];
        [self.navigationController   pushViewController:page animated:YES];
    }
   
}



#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    
    [_collectIonView.header endRefreshing];
    [_collectIonView.footer endRefreshing];
    [_tableView.header endRefreshing];
    [_tableView.footer endRefreshing];
    if (tag==SX_SX_queryGoodsCollectInfo) {
        
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            dispatch_async(dispatch_get_main_queue(), ^{
                _totle = [database[@"result"][@"totalResults"] integerValue];
                if (_totle > PageSize) {
                    __weak __typeof(self) weakSelf = self;
                    if (!self.tableView.footer) {
                        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                        self.collectIonView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                            [weakSelf loadMoreData];
                        }];
                    }
                }
                if (self.pageNO == 1) {
                    [self.goodsArray removeAllObjects];
                }
                NSArray *arr = database[@"result"][@"pageRecord"];
                for (id entity in arr) {
                    [self.goodsArray addObject:entity];
                }
                _collectIonView.dataSource = self;
                _collectIonView.delegate = self;
                [_collectIonView reloadData];
                
            });
        }
    }else if (tag ==SX_SX_queryStoreCollectInfo ){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            dispatch_async(dispatch_get_main_queue(), ^{
                _storeTotle = [database[@"result"][@"totalResults"] integerValue];
                if (_storeTotle > PageSize) {
                    __weak __typeof(self) weakSelf = self;
                    if (!self.tableView.footer) {
                        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                        self.tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                            [weakSelf loadMoreData];
                        }];
                    }
                }
                if (self.storePageNO == 1) {
                    [self.goodsArray removeAllObjects];
                }
                NSArray *arr = database[@"result"][@"pageRecord"];
                for (id entity in arr) {
                    [self.goodsArray addObject:entity];
                }
                _tableView.dataSource = self;
                _tableView.delegate = self;
                [_tableView reloadData];
                
            });
        }
    
    
    }
}

-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    
    //
    [self dismissWaitDialog];
    
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
